package com.khotyn.heresy.validator;

import java.util.regex.Pattern;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.khotyn.heresy.bean.RegisterBean;
import com.khotyn.heresy.dao.UserDAO;

/**
 * 验证注册时填写的邮箱、密码是否符合规范
 * 
 * @author 金灵杰
 * 
 */
public class RegisterValidator implements Validator {

	private UserDAO userDAO;

	/**
	 * @param userDAO
	 *            the userDAO to set
	 */
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	/**
	 * 过滤验证器验证的类的类型
	 */
	@Override
	public boolean supports(Class clazz) {
		return RegisterBean.class.equals(clazz);
	}

	/**
	 * 过滤类中的字段
	 */
	@Override
	public void validate(Object obj, Errors errors) {
		RegisterBean registerInfo = (RegisterBean) obj;

		// 验证邮件地址为空
		// ValidationUtils.rejectIfEmptyOrWhitespace(errors,
		// "registerBean.email", "email.empty", "邮件地址不能为空");

		// 验证密码是否为8-12位字母、数字和下划线组合
		if (!Pattern.matches("^(\\w){8,12}$", registerInfo.getPassword())) {
			errors.rejectValue("password", "password.not_fit",
					"密码不符要求（8－12位字母、数字和下划线组合）");
		}

		// 验证邮件地址是否符合规范
		if (!Pattern.matches("^[\\w][\\w\\-\\.]+@[\\w\\-]+(\\.[a-z]+){1,2}$",
				registerInfo.getEmail())) {
			errors.rejectValue("email", "email.not_standard", "邮件地址输入不符合规范");
		}

		// 邮箱已经注册
		String emailAdd = registerInfo.getEmail();
		if (userDAO.selectLoginInfoByEmail(emailAdd) != null) {
			errors.rejectValue("email", "email.already_registered",
					"该邮箱已经注册，请使用该邮箱登录（找回密码）或使用其他邮箱注册");
		}
	}

}
